<?php

/**
 *
 * 商城管理模块
 *
 *
 * This is NOT a freeware, use is subject to license terms
 *
 * @copyright Copyright (C) 2005 - 2099 Cenwor Inc.
 * @license http://www.cenwor.com
 * @link http://www.jishigou.net
 * @author 狐狸<foxis@qq.com>
 * @version $Id: mall.mod.php 3740 2013-05-28 09:38:05Z wuliyong $
 */
if (!defined('IN_JISHIGOU')) {
    exit('invalid request');
}

class ModuleObject extends MasterObject {

    private $order_status = array(
        0 => "未支付",
        1 => "已支付",
        2 => "已发货",
        3 => "已退还",
    );
    private $goods_type = array(
        'entity' => '实体商品',
        'fictitious' => '虚拟商品'
    );
    private $pay_type = array(
        'alipay' => '支付宝',
        'wx' => '微信支付',
        'COD' => '货到付款'
    );
    var $auto_run = true;

    function ModuleObject($config) {
        $this->MasterObject($config);
    }

    function index() {


        include template();
    }

    function setting() {
        $mall = jconf::get('mall');
        $oldmallcredits = $mall['credits'];

        $credits_options = array();
        $credits = jconf::get('credits');
        if ($credits && $credits['ext']) {
            foreach ($credits['ext'] as $_key => $_row) {
                if ($_row['enable'] && $_row['name'] && $_key) {
                    $credits_options[$_key] = array('name' => $_row['name'], 'value' => $_key);
                }
            }
        }
        if (empty($credits_options)) {
            $this->Messager('请先设置积分项', 'admin.php?mod=setting&code=modify_credits');
        }


        if (jget('settingsubmit')) {
            $_mall = jget('mall');
            $mall['enable'] = (int) $_mall['enable'];
            $mall['exchange'] = (int) $_mall['exchange'];
            $mall['post'] = (int) $_mall['post'];

            $mc = $_mall['credits'];
            if ($mc && $credits['ext'][$mc]['enable']) {
                $mall['credits'] = $mc;

                $mall['credits_name'] = $credits['ext'][$mc]['name'];
            }

            $mall['rule'] = jget('rule');

            jconf::set('mall', $mall);

            if ($mall['credits'] != $oldmallcredits) {
                $sets = array();
                $rule = array('extcredits1', 'extcredits2', 'extcredits3', 'extcredits4', 'extcredits5', 'extcredits6', 'extcredits7', 'extcredits8');
                foreach ($rule as $v) {
                    if ($mall['credits'] == $v) {
                        $sets[] = "`$v`='1'";
                    } else {
                        $sets[] = "`$v`='0'";
                    }
                }
                DB::Query("update " . TABLE_PREFIX . "credits_rule set " . implode(" , ", $sets) . " where `action`='convert' or `action`='unconvert'");
                $credits_rule = jconf::get('credits_rule');
                foreach ($credits_rule as $ck => $cv) {
                    if (in_array($ck, array('convert', 'unconvert'))) {
                        foreach ($cv as $_k => $_v) {
                            if (!in_array($_k, array('rid', 'rulename', 'action', 'cycletype'))) {
                                unset($credits_rule[$ck][$_k]);
                            }
                        }
                        $credits_rule[$ck][$mall['credits']] = '1';
                    }
                }
                jconf::set('credits_rule', $credits_rule);
            }

            $this->Messager('设置成功');
        }



        $mall_enable_radio = $this->jishigou_form->YesNoRadio('mall[enable]', (int) $mall['enable']);
        $feed_exchange_radio = $this->jishigou_form->YesNoRadio('mall[exchange]', (int) $mall['exchange']);
        $feed_post_radio = $this->jishigou_form->YesNoRadio('mall[post]', (int) $mall['post']);
        $mall_credits_select = $this->jishigou_form->Select('mall[credits]', $credits_options, $mall['credits']);
        $mall_rule = $this->jishigou_form->Textarea('rule', $mall['rule']);

        include template();
    }

    function manage() {
        $p = array(
            'perpage' => 100,
            'page_mall' => 'admin.php?mod=mall&code=manage',
            'sql_order' => ' `id` DESC ',
        );
        $id = jget('id', 'int');
        if ($id > 0) {
            $p['id'] = $id;
            $p['page_mall'] .= "&id=$id";
        }
        $key = jget('key');
        if ($key) {
            $p['key'] = $key;
            $p['page_mall'] .= "&key=$key";
        }
        $mall = jget('mall');
        if ($mall) {
            $p['sql_where'] = " MATCH (`mall`) AGAINST ('{$mall}') ";
            $p['page_mall'] .= "&mall=$mall";
        }
        $site_id = jget('site_id', 'int');
        if ($site_id > 0) {
            $p['site_id'] = $site_id;
            $p['page_mall'] .= "&site_id=$site_id";
        }
        $order = jget('order');
        if ($order && in_array($order, array('dateline', 'open_times'))) {
            $p['sql_order'] = " `{$order}` DESC ";
            $p['page_mall'] .= "&order=$order";
        }
        $rets = jlogic('mall')->get($p);

        include template();
    }

    function do_manage() {
        $id = jget('id', 'int');
        $ids = jget('ids');
        if (!$ids && $id < 1) {
            $this->Messager('请先指定要操作的对象');
        }
        $ids = (array) ($id > 0 ? $id : $ids);

        $info = array();
        if ($id > 0) {
            $info = jlogic('mall')->get_info_by_id($id);
        }

        $action = jget('action');
        if ('delete' == $action) {
            jlogic('mall')->delete(array('id' => $ids));
        } elseif ('status') {
            $status = jget('status', 'int');
            jlogic('mall')->set_status($ids, $status);
            if ($info && ($site = jlogic('site')->get_info_by_id($info['site_id']))) {
                if (jget('confirm')) {
                    jlogic('mall')->set_status(array('site_id' => $site['id']), $status);
                    jlogic('site')->set_status(array('id' => $site['id']), $status);
                } else {
                    $mall = "admin.php?mod=mall&code=do_manage&action=status&status=$status&id=$id&confirm=1";
                    $this->Messager("已经设置成功，<a href='{$mall}'>点此可以将此站点 {$site['host']} 下的所有URL链接地址都设置为相同的状态</a><br />（默认不点击时将为您跳转回列表页面）。", '', 5);
                }
            }
        }

        $this->Messager('操作成功', 'admin.php?mod=mall&code=manage');
    }

    public function goods_list() {
        $config = jconf::get('mall');
        $sql_where = ' 1 ';
        $style = jget('style');
        if(isset($style) && $style != '' ){
            $sql_where .= " and style = '$style' ";
        }
        $name = jget('name');
        if(isset($name) && $name != '' ){
            $sql_where .= " and name like '%$name%' ";
        }
        $list = jlogic("mall")->get_goods_list('',$sql_where);
        $goods_type = $this->goods_type;
        include template();
    }

    public function add_goods() {
        $config = jconf::get('mall');
        include template();
    }

    public function do_add_goods() {
        $data = jget("data");
        $images = jget("files");
        $topic = jget("topic");
        $property_key = jget("property_key");
        $property_val = jget("property_val");
        $property_array = array();
        if($property_key != '' && $property_val != ''){
            foreach ($property_key as $key => $value) {
                if($value != '' && $property_val[$key] != ''){
                    $property_array[$key]['key'] = $value;
                    $property_array[$key]['val'] = $property_val[$key];
                }
            }
        }
        $specify_key = jget("specify_key");
        $specify_val = jget("specify_val");
        $specify_array = array();
        if($specify_key != '' && $specify_val != ''){
            foreach ($specify_key as $key => $value) {
                if($value != '' && $specify_val[$key] != ''){
                    $specify_array[$key]['key'] = $value;
                    $specify_array[$key]['val'] = $specify_val[$key];
                }
            }
        }
        $data = $this->check_data($data);
        $image_src = '';
        if ($_FILES['image']) {
            $image = jlogic('image')->upload(array('pic_field' => 'image'));
            $image['photo'] = $image['site_url'] ? $image['site_url'] . '/' . str_replace('./', '', $image['photo']) : $image['photo'];
            $image_src = (string) $image['photo'];
        }
        $data['image'] = $image_src;
        $img_arr = array();
        if(count($images)>0){
            foreach ($images as $key => $value) {
                $img_arr[$key]['img'] = $value;
                $img_arr[$key]['tid'] = $topic[$key];
            }
        }
        $data['images'] = json_encode($img_arr);
        $data['property'] = json_encode($property_array, JSON_UNESCAPED_UNICODE);
        $data['specifications'] = json_encode($specify_array, JSON_UNESCAPED_UNICODE);
        $r = jlogic("mall")->add_goods($data);
        if ($r) {
            if($data['style'] == 'entity'){
                $arr = array(
                    'brand_name' => '',
                    'type_name' => $this->goods_type[$data['style']],
                    'goods_name' => $data['name'],
                    'goods_bn' => $data['sn'],
                    'unit' => '',
                    'is_serial' => '',
                    'sale_price' => $data['price'],
                    'cost_price' => '',
                    'product_bn' => $data['product_bn'],
                    'barcode' => $data['barcode'],
                    'weight' => $data['weight'],
                    'method' => 'goods.add'
                );
                $rs = jclass('erp')->getcontent($arr);
            }
            
            
            $this->Messager("添加商品成功");
        } else {
            $this->Messager("添加商品失败");
        }
    }
    
    public function modify_goods() {
        $config = jconf::get('mall');
        $id = jget("id", 'int');
        if ($id < 1) {
            $this->Messager("请选择你要修改的商品");
        }
        $info = jlogic("mall")->get_info($id);
        $images = array();
        if($info['images'] != ''){
            $images = json_decode($info['images'],TRUE);
        }
        $propertys = array();
        if($info['property'] != ''){
            $propertys = json_decode($info['property'],TRUE);
        }
        $specifys = array();
        if($info['specifications'] != ''){
            $specifys = json_decode($info['specifications'],TRUE);
        }
        include template();
    }

    public function deltes_goods() {

        $goods_id = jget("id");

        $r = jtable('mall_goods')->delete($goods_id);
        return $r ? $this->Messager('删除商品成功', 'admin.php?mod=mall&code=goods_list') : $this->Messager("删除商品失败");
    }

    public function do_modify_goods() {
        $data = jget("data");
        $gid = jget("id");
        $data = $this->check_data($data);

        if ($_FILES['image']['error'] === 0) {
            $image = jlogic('image')->upload(array('pic_field' => 'image'));
            $image['photo'] = $image['site_url'] ? $image['site_url'] . '/' . str_replace('./', '', $image['photo']) : $image['photo'];
            $image_src = (string) $image['photo'];
            $data['image'] = $image_src;
        }
        $images = jget("files");
        $topic = jget("topic");
        $img_arr = array();
        if(count($images)>0){
            foreach ($images as $key => $value) {
                $img_arr[$key]['img'] = $value;
                $img_arr[$key]['tid'] = $topic[$key];
            }
        }
        $data['images'] = json_encode($img_arr);
        $property_key = jget("property_key");
        $property_val = jget("property_val");
        $property_array = array();
        if($property_key != '' && $property_val != ''){
            foreach ($property_key as $key => $value) {
                if($value != '' && $property_val[$key] != ''){
                    $property_array[$key]['key'] = $value;
                    $property_array[$key]['val'] = $property_val[$key];
                }
            }
        }
        $specify_key = jget("specify_key");
        $specify_val = jget("specify_val");
        $specify_array = array();
        if($specify_key != '' && $specify_val != ''){
            foreach ($specify_key as $key => $value) {
                if($value != '' && $specify_val[$key] != ''){
                    $specify_array[$key]['key'] = $value;
                    $specify_array[$key]['val'] = $specify_val[$key];
                }
            }
        }
        $data['property'] = json_encode($property_array, JSON_UNESCAPED_UNICODE);
        $data['specifications'] = json_encode($specify_array, JSON_UNESCAPED_UNICODE);
        $r = jlogic("mall")->modify_goods($gid, $data);
        if($r){
            if($data['style'] == 'entity'){
                $arr = array(
                    'brand_name' => '',
                    'type_name' => $this->goods_type[$data['style']],
                    'goods_name' => $data['name'],
                    'goods_bn' => $data['sn'],
                    'unit' => '',
                    'is_serial' => '',
                    'sale_price' => $data['price'],
                    'cost_price' => '',
                    'product_bn' => $data['product_bn'],
                    'barcode' => $data['barcode'],
                    'weight' => $data['weight'],
                    'method' => 'goods.edit'
                );
                jclass('erp')->getcontent($arr);
            }
        }
        return $r ? $this->Messager("编辑商品成功") : $this->Messager("编辑商品失败");
    }

    protected function check_data($data) {
        $config = jconf::get('mall');
        $data['name'] = trim($data['name']);
        if (!$data['name']) {
            $this->Messager("请填写名字");
        }
        $style = $data['style'];
        if($style == 'entity'){
            if (number_format($data['price'], 2) == '0.00') {
                $this->Messager("请填写所需金额");
            } else {
                $data['price'] = $data['price'];
                $data['gold'] = (int) $data['gold'];
            }
        }else{
            if ((int) $data['gold'] < 1) {
                $this->Messager("请填写所需" . $config['credits_name']);
            } else {
                $data['gold'] = (int) $data['gold'];
                $data['price'] = 0;
            }
        }
        if($data['expire'] !=''){
            $data['expire'] = strtotime($data['expire']);
        }
        if ((int) $data['total'] < 1) {
            $this->Messager("请填写总商品数");
        } else {
            $data['total'] = (int) $data['total'];
        }

        return $data;
    }

    public function order_list() {

        $gid = jget("gid");
        $list = jlogic('mall_order')->get_list($gid);

        $goods_info = jtable('mall_goods')->info(array('id' => $gid));
        foreach ($list['list'] as $k => $one) {
            $list['list'][$k]['add_time'] = date('Y-m-d H:i:m', $one['add_time']);
        }
        $goods_type = $this->goods_type;
        $pay_status = $this->order_status;
        $order_status = -1;
        include template();
    }
    
    public function order_detail() {
        $config = jconf::get('mall');
        $id = jget("id", 'int');
        if ($id < 1) {
            $this->Messager("请选择你要查看的订单");
        }
        $info = jlogic("mall_order")->get_info($id);
        $pay_status = $this->order_status;
        include template();
    }
    public function search_order() {
        $goods_name = jget("goods_name");
        $goods_style = jget("goods_style");
        $ordersid = jget("ordersid");
        $sn = jget("sn");
        $user_nickname = jget("user_nickname");
        $order_status = jget("order_state", 'int');

        if ($goods_name) {
            $goods_info = jtable('mall_goods')->info(array('name' => trim($goods_name)));
            $sql_str['goods_id'] = $goods_info['id'];
        }
        if ($goods_style) {
            $sql_str['goods_style'] = $goods_style;
        }
        if ($ordersid) {
            $sql_str['ordersid'] = $ordersid;
        }
        if ($sn) {
            $sql_str['sn'] = $sn;
        }
        if ($user_nickname) {
            $members = jsg_get_member(trim($user_nickname));
            $sql_str['uid'] = $members['uid'];
        }
        if ($order_status >= 0) {
            $sql_str['status'] = $order_status;
        }
        $timefrom = jget('timefrom');
        if ($timefrom) {
            $str_time_from = strtotime($timefrom);
            $sql_str['>=@add_time'] = $str_time_from;
        }
        $timeto = jget('timeto');
        if ($timeto) {
            $str_time_to = strtotime($timeto);
            $sql_str['<=@add_time'] = $str_time_to;
        }
        $sql_str['sql_order'] = 'id desc';
        //$sql_str['page_num'] = 20;
        $list = jtable('mall_order')->get($sql_str);
        foreach ($list['list'] as $k => $one) {
            $list['list'][$k]['add_time'] = date('Y-m-d H:i:m', $one['add_time']);
            $list['list'][$k]['pay_time'] = date('Y-m-d H:i:m', $one['pay_time']);
        }
        $goods_type = $this->goods_type;
        $pay_status = $this->order_status;
        $pay_type = $this->pay_type;
        $do = jget('do');
        if($do == 'order_export'){
            //下面是总结的几个使用方法
            include_once $_SERVER["DOCUMENT_ROOT"] . '/PHPExcel.php';
            include_once $_SERVER["DOCUMENT_ROOT"] . '/PHPExcel/Writer/Excel2007.php';
            $objPHPExcel = new PHPExcel();

            // Set document properties
            $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
                    ->setLastModifiedBy("Maarten Balliauw")
                    ->setTitle("Office 2007 XLSX Test Document")
                    ->setSubject("Office 2007 XLSX Test Document")
                    ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
                    ->setKeywords("office 2007 openxml php")
                    ->setCategory("Test result file");


            // Add some data
            //                *:订单号	 *:支付方式    *:下单时间	  *:付款时间    *:配送方式	   *:配送费用    *:来源店铺编号   *:订单附言	    *:收货人姓名	*:收货地址省份	*:收货地址城市	*:收货地址区/县	*:收货详细地址	*:收货人固定电话	*:电子邮箱	*:收货人移动电话	*:邮编	*:货到付款	*:是否开发票	*:发票抬头	*:税金(非开票总额)	*:优惠方案	*:订单优惠金额	*:商品优惠金额	*:折扣	*:返点积分	*:商品总额	*:订单总额	*:买家会员名	*:订单类型	*:订单备注	*:商品重量	*:发票号	*:周期购
            $headArr = array('*:订单号', '*:支付方式', '*:下单时间', '*:付款时间', '*:配送方式', '*:配送费用', '*:来源店铺编号', '*:订单附言', '*:收货人姓名', '*:收货地址省份', '*:收货地址城市', '*:收货地址区/县', '*:收货详细地址', '*:收货人固定电话', '*:电子邮箱', '*:收货人移动电话', '*:邮编', '*:货到付款', '*:是否开发票', '*:发票抬头', '*:税金(非开票总额)', '*:优惠方案', '*:订单优惠金额', '*:商品优惠金额', '*:折扣', '*:返点积分', '*:商品总额', '*:订单总额', '*:买家会员名', '*:订单类型', '*:订单备注', '*:商品重量', '*:发票号', '*:周期购');
            $key = 0;
            //print_r($headArr);exit;
            foreach($headArr as $v){
                //注意，不能少了。将列数字转换为字母\
                $colum = \PHPExcel_Cell::stringFromColumnIndex($key);
                $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.'1', $v);
                $key += 1;
            }
            // Rename worksheet
            $objPHPExcel->getActiveSheet()->setTitle('Simple');
            //$objPHPExcel->getActiveSheet()->getDefaultStyle()->getFont()->setName('宋体');
            // Set active sheet index to the first sheet, so Excel opens this as the first sheet

            $column = 2;
            $objActSheet = $objPHPExcel->getActiveSheet();
            foreach ($list['list'] as $keys => $row) { //行写入
                $i = 0;
                $array = array($row['sn'], $pay_type[$row['pay_type']], $row['add_time'], $row['pay_time'], '', '', 'somall', '', $row['receiver_name'], $row['receiver_state'], $row['receiver_city'], $row['receiver_district'], $row['address'], '', '', $row['receiver_tel'], $row['postcode'],'','','','','','','','','',$row['goods_num']*$row['goods_price'],$row['pay_price'],$row['username'],$goods_type[$row['goods_style']],'','','','');

                $span = 0;
                foreach($array as $keyName=>$value){// 列写入
                    $j = \PHPExcel_Cell::stringFromColumnIndex($span);
                    if($span == 0){
                        $objActSheet->setCellValueExplicit($j.$column, $value,PHPExcel_Cell_DataType::TYPE_STRING);
                    }else{
                        $objActSheet->setCellValue($j.$column, $value);
                    }
                    
                    $span++;
                }
                $column++;
            }
            
            $headArr_mall = array('*:订单号', '*:商品货号', '*:商品名称', '*:购买单位', '*:商品规格', '*:购买数量', '*:商品原价', '*:销售价');
            $key_mall = 0;
            //print_r($headArr);exit;
            foreach($headArr_mall as $v){
                //注意，不能少了。将列数字转换为字母\
                $colum = \PHPExcel_Cell::stringFromColumnIndex($key_mall);
                $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.$column, $v);
                $key_mall += 1;
            }
            // Rename worksheet
            $objPHPExcel->getActiveSheet()->setTitle('Simple');
            //$objPHPExcel->getActiveSheet()->getDefaultStyle()->getFont()->setName('宋体');
            // Set active sheet index to the first sheet, so Excel opens this as the first sheet

            $column = $column+1;
            foreach ($list['list'] as $keys => $row) { //行写入
                $i = 0;
                $array = array($row['sn'], '', $row['goods_name'], '', '', $row['goods_num'], $row['goods_price'], $row['goods_price']);

                $span = 0;
                foreach($array as $keyName=>$value){// 列写入
                    $j = \PHPExcel_Cell::stringFromColumnIndex($span);
                    if($span == 0){
                        $objActSheet->setCellValueExplicit($j.$column, $value,PHPExcel_Cell_DataType::TYPE_STRING);
                    }else{
                        $objActSheet->setCellValue($j.$column, $value);
                    }
                    $span++;
                }
                $column++;
            }
            $fileName = "订单-".time() . '.xls';
            // Redirect output to a client’s web browser (Excel5)
            header("Content-Type: application/vnd.ms-excel; charset=UTF-8");
            header("Content-Disposition: attachment; filename=\"$fileName\"");
            header('Cache-Control: max-age=0');
            // If you're serving to IE 9, then the following may be needed
            header('Cache-Control: max-age=1');

            // If you're serving to IE over SSL, then the following may be needed
            header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
            header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
            header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
            header('Pragma: public'); // HTTP/1.0

            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
            $objWriter->save('php://output');
            exit;
        }else if($do == 'order_mall_export'){
            //下面是总结的几个使用方法
            include_once $_SERVER["DOCUMENT_ROOT"] . '/PHPExcel.php';
            include_once $_SERVER["DOCUMENT_ROOT"] . '/PHPExcel/Writer/Excel2007.php';
            $objPHPExcel = new PHPExcel();

            // Set document properties
            $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
                    ->setLastModifiedBy("Maarten Balliauw")
                    ->setTitle("Office 2007 XLSX Test Document")
                    ->setSubject("Office 2007 XLSX Test Document")
                    ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
                    ->setKeywords("office 2007 openxml php")
                    ->setCategory("Test result file");


            // Add some data
            $headArr = array('*:订单号', '*:商品货号', '*:商品名称', '*:购买单位', '*:商品规格', '*:购买数量', '*:商品原价', '*:销售价');
            $key = 0;
            //print_r($headArr);exit;
            foreach($headArr as $v){
                //注意，不能少了。将列数字转换为字母\
                $colum = \PHPExcel_Cell::stringFromColumnIndex($key);
                $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.'1', $v);
                $key += 1;
            }
            // Rename worksheet
            $objPHPExcel->getActiveSheet()->setTitle('Simple');
            //$objPHPExcel->getActiveSheet()->getDefaultStyle()->getFont()->setName('宋体');
            // Set active sheet index to the first sheet, so Excel opens this as the first sheet

            $column = 2;
            $objActSheet = $objPHPExcel->getActiveSheet();
            foreach ($list['list'] as $keys => $row) { //行写入
                $i = 0;
                $array = array($row['sn'], '', $row['goods_name'], '', '', $row['goods_num'], $row['goods_price'], $row['goods_price']);

                $span = 0;
                foreach($array as $keyName=>$value){// 列写入
                    $j = \PHPExcel_Cell::stringFromColumnIndex($span);
                    $objActSheet->setCellValue($j.$column, $value);
                    $span++;
                }
                $column++;
            }
            $fileName = "订单详情-".time() . '.xls';
            // Redirect output to a client’s web browser (Excel5)
            header("Content-Type: application/vnd.ms-excel; charset=UTF-8");
            header("Content-Disposition: attachment; filename=\"$fileName\"");
            header('Cache-Control: max-age=0');
            // If you're serving to IE 9, then the following may be needed
            header('Cache-Control: max-age=1');

            // If you're serving to IE over SSL, then the following may be needed
            header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
            header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
            header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
            header('Pragma: public'); // HTTP/1.0

            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
            $objWriter->save('php://output');
            exit;
        }else{
            include template('admin/mall_order_list');
        }
        
    }
    function modify_slide_mall() {
        $slide_config = jconf::get('slide_mall');
        $slide_list = $slide_config['list'];
        include(template('admin/setting_slide_mall'));
    }

    function do_modify_slide_mall() {
        $slide_config = jconf::get('slide_mall');
        $slide_list = array();
        $image_src = '';
        if ($_FILES['image']['error'] === 0) {
            $image = jlogic('image')->upload(array('pic_field' => 'image'));
            $image['photo'] = $image['site_url'] ? $image['site_url'] . '/' . str_replace('./', '', $image['photo']) : $image['photo'];
            $image_src = (string) $image['photo'];
            $slide_list['advert'] = $image_src;
        }else{
            $slide_list['advert'] = $slide_config['list']['advert'];
        }
        
        $images = jget("files");
        $topic = jget("topic");
        $img_arr = array();
        if(count($images)>0){
            foreach ($images as $key => $value) {
                $img_arr[$key]['img'] = $value;
                $img_arr[$key]['tid'] = $topic[$key];
            }
        }
        $slide_list['images'] = $img_arr;
        $slide['list'] = $slide_list;
        if ($slide != $slide_config) {
            jconf::set('slide_mall', $slide);
        }

        $this->Messager("设置成功");
    }
    public function express_import() {
        $msg = '';
        $filename = $_FILES['file']['tmp_name']; //获取文件数据
        $myfile = '';
        if (fopen($filename, 'r')){
            $myfile = fopen($filename, 'r'); //打开文件
        }
        $result = $this->input_csv($myfile); //解析文件
        $len_result = count($result); //数据行数
        if ($len_result < 2) {
            $msg = 'null';
        }else{
            foreach ($result as $key => $val) {//文件字段数组
                if ($key > 0) {
                    if($val[0] != ''){
                        $sn = $val[0];
                        $order_info = jtable('mall_order')->info(array('sn'=>$sn));
                        if(is_array($order_info)){
                            if($order_info['logisticsname'] == '' && $order_info['logisticsid'] == ''){
                                $logisticsname = $val[12];
                                $logisticsid = $val[1];
                                jtable('mall_order')->update(array('logisticsname'=>$logisticsname,'logisticsid'=>$logisticsid,'status'=>2),array('sn'=>$sn));
                                $savedata = array(
                                    'uid' => $order_info['uid'],
                                    'order_id' => $order_info['id'],
                                    'status' => 2,
                                    'dateline' => time()
                                );
                                jtable('mall_order_action')->insert($savedata);
                            }
                        }
                    }
                }
            }
            $msg = 'success';
        }
        fclose($myfile); //关闭指针
        if($msg == 'success'){
            $this->Messager("上传成功");
        }else{
            $this->Messager("上传失败");
        }
        
    }
    public function input_csv($handle) {
        $out = array();
        $n = 0;

        while ($data = fgetcsv($handle, 10000)) {
            $num = count($data);
            for ($i = 0; $i < $num; $i++) {
                $out[$n][$i] = $data[$i];
            }
            $n++;
        }

        return $out;
    }
}

?>
